package com.wenzil.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wenzil.common.utils.HttpUtils;
import com.wenzil.gulimall.member.dao.MemberLevelDao;
import com.wenzil.gulimall.member.entity.MemberLevelEntity;
import com.wenzil.gulimall.member.exception.PhoneExistException;
import com.wenzil.gulimall.member.exception.UsernameException;
import com.wenzil.gulimall.member.vo.MemberLoginVo;
import com.wenzil.gulimall.member.vo.MemberRegistVo;
import com.wenzil.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wenzil.common.utils.PageUtils;
import com.wenzil.common.utils.Query;

import com.wenzil.gulimall.member.dao.MemberDao;
import com.wenzil.gulimall.member.entity.MemberEntity;
import com.wenzil.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(memberEntity.getId());

        // 检查用户名和手机号释放唯一，为了让Controller能感知异常，异常机制
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());

        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setNickname(vo.getUserName());
        // 密码要进行加密存储
        memberEntity.setPassword("");
        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginact = vo.getLoginact();
        String password = vo.getPassword();
        // 1、去数据库查询 select * from ums_member where username=? or mobile=?
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginact).or().eq("mobile", loginact));
        if (memberEntity == null) {
            // 登录失败
            return null;
        } else {
            String passwordDb = vo.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if (matches) {
                return memberEntity;
            } else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        String uid = socialUser.getUid();
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            // 这个用户已经注册
            MemberEntity updateMemberEntity = new MemberEntity();
            updateMemberEntity.setId(memberEntity.getId());
            updateMemberEntity.setAccessToken(socialUser.getAccess_token());
            updateMemberEntity.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.updateById(updateMemberEntity);
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        } else {
            MemberEntity registMemberEntity = new MemberEntity();
            try {
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("access_token", socialUser.getAccess_token());
                hashMap.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), new HashMap<String, String>());
                if (response.getStatusLine().getStatusCode() == 200) {
                    // 查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    // ....
                    registMemberEntity.setNickname(name);
                    registMemberEntity.setGender("m".equalsIgnoreCase(gender)?1:0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            registMemberEntity.setSocialUid(socialUser.getUid());
            registMemberEntity.setAccessToken(socialUser.getAccess_token());
            registMemberEntity.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.insert(registMemberEntity);
            return registMemberEntity;
        }
    }
}
